package com.sunshine.wheel.study.netty.chat.util;

import com.sunshine.wheel.study.netty.chat.protocol.IMMessage;
import com.sunshine.wheel.study.netty.chat.protocol.IMPEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义消息编解码工具类
 */
public class MsgCodecUtils {

    private static final Pattern CONTENT_PATTERN = Pattern.compile("^\\[(.*)\\](\\s\\-\\s(.*))?");

    /**
     * 将自定义消息转换成字符串
     *
     * @param msg 自定义消息
     * @return
     */
    public static String encode(IMMessage msg) {
        if (msg == null) {
            return StringUtils.EMPTY;
        }
        String prefix = "[" + msg.getCmd() + "]" + "[" + msg.getTime() + "]";

        if (IMPEnum.LOGIN.getValue().equalsIgnoreCase(msg.getCmd()) ||
                IMPEnum.CHAT.getValue().equalsIgnoreCase(msg.getCmd()) ||
                IMPEnum.FLOWER.getValue().equalsIgnoreCase(msg.getCmd())) {
            prefix += ("[" + msg.getSender() + "]");
        } else if (IMPEnum.SYSTEM.getValue().equalsIgnoreCase(msg.getCmd())) {
            prefix += ("[" + msg.getOnline() + "]");
        }
        if (StringUtils.isNotBlank(msg.getContent())) {
            prefix += (" - " + msg.getContent());
        }

        return prefix;
    }

    /**
     * 字符串解析成自定义即时通信协议
     *
     * @param msg 自定义消息
     * @return
     */
    public static IMMessage decode(String msg) {
        if (StringUtils.isBlank(msg)) {
            return null;
        }

        Matcher matcher = CONTENT_PATTERN.matcher(msg);
        String header = "";
        String content = "";
        if (matcher.matches()) {
            header = matcher.group(1);
            content = matcher.group(3);
        }

        String[] heards = header.split("\\]\\[");
        long time = 0;
        try {
            time = Long.parseLong(heards[1]);
        } catch (Exception e) {
        }

        String nickName = heards[2];
        nickName = nickName.length() < 10 ? nickName : nickName.substring(0, 9);

        if (msg.startsWith("[" + IMPEnum.LOGIN.getValue() + "]")) {
            return new IMMessage(heards[0], time, nickName);
        } else if (msg.startsWith("[" + IMPEnum.CHAT.getValue() + "]")) {
            return new IMMessage(heards[0], time, nickName, content);
        } else if (msg.startsWith("[" + IMPEnum.FLOWER.getValue() + "]")) {
            return new IMMessage(heards[0], time, nickName);
        } else {
            return null;
        }
    }

}
